﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Cyss.Core
{
    /// <summary>
    /// 加密解密帮助类
    /// </summary>
    public class EncryptHelper
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static String MD5Encrypt(string input)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "");
            }
        }

        /// <summary>
        /// 一个简单的加密算法，因   blazor 不支持 aes rsa加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string CustomEncrypt(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }
            byte[] b = System.Text.Encoding.UTF8.GetBytes(input);
            input = Convert.ToBase64String(b);
            Random random = new Random();
            int index = input.Length / 2;
            input = input.Insert(index, ((char)random.Next(65, 90)).ToString());
            byte[] b2 = System.Text.Encoding.UTF8.GetBytes(input);
            input = Convert.ToBase64String(b2);
            return input;
        }

        /// <summary>
        /// 自定义解密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string CustomDecrypt(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }
            byte[] b = Convert.FromBase64String(input);
            input = System.Text.Encoding.UTF8.GetString(b);
            if (input.Length % 2 == 0)
            {
                input = input.Remove(input.Length / 2 - 1);
            }
            else
            {
                input = input.Remove(input.Length / 2, 1);
            }
            byte[] b2 = Convert.FromBase64String(input);
            return System.Text.Encoding.UTF8.GetString(b2);


        }

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="input"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AESEncrypt(string input, string key)
        {
            return CustomEncrypt(input);
            var encryptKey = Encoding.UTF8.GetBytes(key);

            using (var aesAlg = Aes.Create())
            {

                using (var encryptor = aesAlg.CreateEncryptor(encryptKey, aesAlg.IV))
                {
                    using (var msEncrypt = new MemoryStream())
                    {
                        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor,
                            CryptoStreamMode.Write))

                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(input);
                        }

                        var iv = aesAlg.IV;

                        var decryptedContent = msEncrypt.ToArray();

                        var result = new byte[iv.Length + decryptedContent.Length];

                        Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                        Buffer.BlockCopy(decryptedContent, 0, result,
                            iv.Length, decryptedContent.Length);

                        return Convert.ToBase64String(result);
                    }
                }
            }
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="input"></param>
        /// <param name="key"></param>
        /// <returns></returns>

        public static string AESDecrypt(string input, string key)
        {
            return CustomDecrypt(input);
            var fullCipher = Convert.FromBase64String(input);

            var iv = new byte[16];
            var cipher = new byte[fullCipher.Length - iv.Length];

            Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, fullCipher.Length - iv.Length);
            var decryptKey = Encoding.UTF8.GetBytes(key);

            using (var aesAlg = Aes.Create())
            {
                using (var decryptor = aesAlg.CreateDecryptor(decryptKey, iv))
                {
                    string result;
                    using (var msDecrypt = new MemoryStream(cipher))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt,
                            decryptor, CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                result = srDecrypt.ReadToEnd();
                            }
                        }
                    }

                    return result;
                }
            }
        }

        /// <summary>
        /// 随机加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string RandomEncrypt(string input)
        {
            string time = DateTime.UtcNow.ToFileTimeUtc().ToString();
            input = AESEncrypt(input, "abcdefghabcdefgh");
            input = time.Length.ToString() + "-" + input + "-" + time;
            return AESEncrypt(time, "abcdefghabcdefgh");
        }

        /// <summary>
        /// 随机解密
        /// </summary>
        /// <returns></returns>
        public static string RandomDecrypt(string input)
        {
            input = AESDecrypt(input, "abcdefghabcdefgh");
            string[] vs = input.Split('-');
            if (vs.Length < 3)
            {
                throw new Exception("decrypt error");
            }
            return AESDecrypt(vs[1], "abcdefghabcdefgh");
        }

        public static string UrlParameterEncrypt(string input)
        {
            input = "1234567890" + input + "0987654321" + DateTime.Now.ToFileTimeUtc().ToString();
            return string.Empty;
        }

        public static string UrlParameterDecrypt(string input)
        {
            return string.Empty;
        }



        #region 非对称加密

        /// <summary>
        /// 随机生成ras加密的  公钥和私钥
        /// </summary>
        private static void GenerateKeyPair()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            using (StreamWriter writer = new StreamWriter("PrivateKey.xml", false))  //这个文件要保密...
            {
                writer.WriteLine(rsa.ToXmlString(true));
            }
            using (StreamWriter writer = new StreamWriter("PublicKey.xml", false))
            {
                writer.WriteLine(rsa.ToXmlString(false));

            }
        }

        /// <summary>
        /// RSA 加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="PublicKey"></param>
        /// <returns></returns>
        public static string RSAEncryptData(string data, string PublicKey)
        {
            if (string.IsNullOrEmpty(data))
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(PublicKey))
            {
                throw new ArgumentException("Invalid Public Key");
            }

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                var inputBytes = Encoding.UTF8.GetBytes(data);//有含义的字符串转化为字节流
                rsaProvider.FromXmlString(PublicKey);//载入公钥
                int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度
                var buffer = new byte[bufferSize];
                using (MemoryStream inputStream = new MemoryStream(inputBytes),
                     outputStream = new MemoryStream())
                {
                    while (true)
                    { //分段加密
                        int readSize = inputStream.Read(buffer, 0, bufferSize);
                        if (readSize <= 0)
                        {
                            break;
                        }

                        var temp = new byte[readSize];
                        Array.Copy(buffer, 0, temp, 0, readSize);
                        var encryptedBytes = rsaProvider.Encrypt(temp, false);
                        outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    }
                    return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
                }

            }
        }

        /// <summary>
        /// RSA 解密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="PrivateKey"></param>
        /// <returns></returns>
        public static string RSADecryptData(string data, string PrivateKey)
        {
            if (string.IsNullOrEmpty(data))
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(PrivateKey))
            {
                throw new ArgumentException("Invalid Private Key");
            }

            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                var inputBytes = Convert.FromBase64String(data);
                rsaProvider.FromXmlString(PrivateKey);
                int bufferSize = rsaProvider.KeySize / 8;
                var buffer = new byte[bufferSize];
                using (MemoryStream inputStream = new MemoryStream(inputBytes),
                     outputStream = new MemoryStream())
                {
                    while (true)
                    {
                        int readSize = inputStream.Read(buffer, 0, bufferSize);
                        if (readSize <= 0)
                        {
                            break;
                        }

                        var temp = new byte[readSize];
                        Array.Copy(buffer, 0, temp, 0, readSize);
                        var rawBytes = rsaProvider.Decrypt(temp, false);
                        outputStream.Write(rawBytes, 0, rawBytes.Length);
                    }
                    return Encoding.UTF8.GetString(outputStream.ToArray());
                }
            }

        }

        #endregion


    }
}
